/**
 * 
 */
package org.mspring.mlog.utils;

import java.io.File;

import org.mspring.platform.exception.BusinessException;
import org.mspring.platform.utils.StringUtils;

/**
 * @author Gao Youbo
 * @since 2013-6-4
 * @description
 * @TODO 关于上传的相关通用类
 */
public class UploadUtils {
    /**
     * 上传文件夹
     */
    public static final String UPLOAD_FOLDER = "/uploads";

    /**
     * 获取上传文件夹的绝对路径
     * 
     * @return
     */
    public static final String getAbsoluteUploadPath() {
        return WebUtils.getRealContextPath(UPLOAD_FOLDER);
    }

    /**
     * 获取上传文件绝对路径
     * 
     * @param relativePath
     *            要上传的文件相对路径
     * @return
     */
    public static final String getAbsoluteUploadPath(String relativePath) {
        if (StringUtils.isBlank(relativePath)) {
            throw new BusinessException("请输入相对路径");
        }
        relativePath = StringUtils.replace(relativePath, "\\", "/");
        if (!relativePath.startsWith("/")) {
            relativePath = "/" + relativePath;
        }
        if (!relativePath.startsWith(UPLOAD_FOLDER)) {
            relativePath = UPLOAD_FOLDER + relativePath;
        }
        return WebUtils.getRealContextPath(relativePath);
    }

    /**
     * 获取上传文件绝对路径
     * 
     * @param relativePath
     * @return
     */
    public static final File getAbsoluteUploadFile(String relativePath) {
        String absolutePath = getAbsoluteUploadPath(relativePath);
        File file = new File(absolutePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        return file;
    }

    /**
     * 获取相对于UPLOAD_FOLDER的路径
     * 
     * @param path
     * @return
     */
    public static final String getRelativeUploadPath(String relativePath) {
        relativePath = StringUtils.replace(relativePath, "\\", "/");
        relativePath = StringUtils.replace(relativePath, "//", "/");
        if (!relativePath.startsWith("/")) {
            relativePath = "/" + relativePath;
        }
        if (relativePath.startsWith(UPLOAD_FOLDER)) {
            relativePath = StringUtils.substringAfter(relativePath, UPLOAD_FOLDER);
        }
        return relativePath;
    }
}
